package com.tanhua.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.service.AdminService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /*请求验证码及图片*/
    @GetMapping("verification")
    public void verification(String uuid,HttpServletResponse response) throws IOException {
        //生成图片和验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(299, 97);
        //获取验证码,存入redis
        redisTemplate.opsForValue().set(uuid, circleCaptcha.getCode());
        //将图片信息发送给前端
        circleCaptcha.write(response.getOutputStream());
    }

    /*登录*/
    @PostMapping("login")
    public ResponseEntity login(@RequestBody Map map){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        Map newMap=adminService.login(username,password,verificationCode,uuid);
        return ResponseEntity.ok(newMap);
    }

    /*用户基本信息*/
    @PostMapping("profile")
    public ResponseEntity profile(){
        Map map=adminService.profile();
        return ResponseEntity.ok(map);
    }

    /*用户登出*/
    @PostMapping("logout")
    public ResponseEntity logout(){
        //删除保存的数据
        AdminHolder.remove();
        return ResponseEntity.ok(null);
    }

}
